<?php

class ProcessController extends Zend_Controller_Action
{

    public function init()
    {

    }

    public function indexAction()
    {
         if(Zend_Auth::getInstance()->hasIdentity()){
              echo "Y";
              exit();
         }else{
                $str="<div id='login_form' style='display:none'><div id='status' align='left' style='margin-top: 8px; width: 310px;'>";
                $str= $str."<center><h1><img src='".Zend_Registry::get('static_path')."images/key.png' align='absmiddle'>&nbsp;LOGIN</h1> <div id='login_response'><!-- spanner --></div> </center>";
                $str= $str ."<form id='loginForm'><label>Email Address</label><input type='text' name='emailAddress' id='emailAddress'><br />";
                $str = $str."<label>Password</label><input type='password' name='password' id='password'><br /><br />";
               $str = $str."<a href='javascript:;' id='login_button' onclick='javascript:login()'><input type='image' src='".Zend_Registry::get('static_path')."images/login-button.jpg' border=0/></a>";
                $str = $str." <div id='ajax_loading'><img align='absmiddle' src='images/spinner.gif'>&nbsp;Processing...</div> </form></div>";
                $str = $str."<div id='forgotpasword'><center><a href='javascript:;' id='forgotPassword'>Forgot Password</a> </center></div></div>";
                 $str = $str."<script>$(document).ready(function(){ $('#forgotPassword').click(function(){window.location='process/forgotpassword';});});</script>";
                echo $str;
                exit();
        }
    }

    public function loginAction()
    {
       try{
               $emailAddress=$_POST['emailAddress'];
               $password=$_POST['password'];
                $authAdapter = $this->getAuthAdapter();

                $authAdapter
                               ->setIdentity($emailAddress)
                              ->setCredential($password);

           $select =  $authAdapter->getDbSelect();
            
           $auth = Zend_Auth::getInstance();

          

           $_result =  $auth->authenticate($authAdapter);

          if( $_result->isValid()) {
              $data = $authAdapter->getResultRowObject(null, 'PASSWORD');
              $auth->getStorage()->write($data);
              echo 'OK';
          }else{
              echo 'Invalid Username or Password';
          }
       
       }catch(Exception $e){
           Zend_Registry::get('logger')->setEventItem('class', __CLASS__)->err($e->getMessage());
           echo 'Technical difficulties occured while Authentication';
       }
        exit();
    }

    public function logoutAction(){
       if(Zend_Auth::getInstance()->hasIdentity()){
           Zend_Auth::getInstance()->clearIdentity();
       }
       $this->_redirect('/index');
    }

    public function privateAction(){
        if(Zend_Auth::getInstance()->hasIdentity()){
            if(Zend_Auth::getInstance()->getStorage()->read()->CHANGE_PASSWORD=="Y"){
                $this->_redirect("/process/changepassword");
            }
            if(Zend_Auth::getInstance()->getStorage()->read()->ADMIN=="Y" && Zend_Auth::getInstance()->getStorage()->read()->RESIDENT !="Y"){
               $this->_redirect('/admin');
            }else{
                $this->_redirect('/resident');
            }
        }else{
             $this->_redirect('/index');
        }
    }

    protected function getAuthAdapter()
    {
            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
            $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                    $authAdapter
                           ->setTableName('TBL_USERS')
                           ->setIdentityColumn('EMAIl_ADDRESS')
                           ->setCredentialColumn('PASSWORD')
                          ->setCredentialTreatment('MD5(?)');

            return $authAdapter;
      }

      public function countryAction(){
          $country_str = array("ABW"=> "Aruba", "AFG"=> "Afghanistan", "AGO"=> "Angola", "AIA"=> "Anguilla", "ALA"=> "Aland Islands", "ALB"=> "Albania", "AND"=> "Andorra", "ANT"=> "Netherlands Antilles", "ARE"=> "United Arab Emirates", "ARG"=> "Argentina", "ARM"=> "Armenia", "ASM"=> "American Samoa", "ATA"=> "Antarctica", "ATF"=> "French Southern Territories", "ATG"=> "Antigua and Barbuda", "AUS"=> "Australia", "AUT"=> "Austria", "AZE"=> "Azerbaijan", "BDI"=> "Burundi", "BEL"=> "Belgium", "BEN"=> "Benin", "BFA"=> "Burkina Faso", "BGD"=> "Bangladesh", "BGR"=> "Bulgaria", "BHR"=> "Bahrain", "BHS"=> "Bahamas", "BIH"=> "Bosnia and Herzegovina", "BLM"=> "Saint Barthelemy", "BLR"=> "Belarus", "BLZ"=> "Belize", "BMU"=> "Bermuda", "BOL"=> "Bolivia", "BRA"=> "Brazil", "BRB"=> "Barbados", "BRN"=> "Brunei Darussalam", "BTN"=> "Bhutan", "BVT"=> "Bouvet Island", "BWA"=> "Botswana", "CAF"=> "Central African Republic", "CAN"=> "Canada", "CCK"=> "Cocos (Keeling) Islands", "CHE"=> "Switzerland", "CHL"=> "Chile", "CHN"=> "China", "CIV"=> "Côte d\’Ivoire", "CMR"=> "Cameroon", "COD"=> "Congo, the Democratic Republic of the", "COG"=> "Congo", "COK"=> "Cook Islands", "COL"=> "Colombia", "COM"=> "Comoros", "CPV"=> "Cape Verde", "CRI"=> "Costa Rica", "CUB"=> "Cuba", "CXR"=> "Christmas Island", "CYM"=> "Cayman Islands", "CYP"=> "Cyprus", "CZE"=> "Czech Republic", "DEU"=> "Germany", "DJI"=> "Djibouti", "DMA"=> "Dominica", "DNK"=> "Denmark", "DOM"=> "Dominican Republic", "DZA"=> "Algeria", "ECU"=> "Ecuador", "EGY"=> "Egypt", "ERI"=> "Eritrea", "ESH"=> "Western Sahara", "ESP"=> "Spain", "EST"=> "Estonia", "ETH"=> "Ethiopia", "FIN"=> "Finland", "FJI"=> "Fiji", "FLK"=> "Falkland Islands (Malvinas)", "FRA"=> "France", "FRO"=> "Faroe Islands", "FSM"=> "Micronesia, Federated States of", "GAB"=> "Gabon", "GBR"=> "United Kingdom", "GEO"=> "Georgia", "GGY"=> "Guernsey", "GHA"=> "Ghana", "GIN"=> "Guinea", "GIB"=> "Gibraltar", "GLP"=> "Guadeloupe", "GMB"=> "Gambia", "GNB"=> "Guinea-Bissau", "GNQ"=> "Equatorial Guinea", "GRC"=> "Greece", "GRD"=> "Grenada", "GRL"=> "Greenland", "GTM"=> "Guatemala", "GUF"=> "French Guiana", "GUM"=> "Guam", "GUY"=> "Guyana", "HKG"=> "Hong Kong", "HMD"=> "Heard Island and McDonald Islands", "HND"=> "Honduras", "HRV"=> "Croatia", "HTI"=> "Haiti", "HUN"=> "Hungary", "IDN"=> "Indonesia", "IMN"=> "Isle of Man", "IND"=> "India", "IOT"=> "British Indian Ocean Territory", "IRL"=> "Ireland", "IRN"=> "Iran, Islamic Republic of", "IRQ"=> "Iraq", "ISL"=> "Iceland", "ISR"=> "Israel", "ITA"=> "Italy", "JAM"=> "Jamaica", "JEY"=> "Jersey", "JOR"=> "Jordan", "JPN"=> "Japan", "KAZ"=> "Kazakhstan", "KEN"=> "Kenya", "KGZ"=> "Kyrgyzstan", "KHM"=> "Cambodia", "KIR"=> "Kiribati", "KNA"=> "Saint Kitts and Nevis", "KOR"=> "Korea, Republic of", "KWT"=> "Kuwait", "LAO"=> "Lao People\’s Democratic Republic", "LBN"=> "Lebanon", "LBR"=> "Liberia", "LBY"=> "Libyan Arab Jamahiriya", "LCA"=> "Saint Lucia", "LIE"=> "Liechtenstein", "LKA"=> "Sri Lanka", "LSO"=> "Lesotho", "LTU"=> "Lithuania", "LUX"=> "Luxembourg", "LVA"=> "Latvia", "MAC"=> "Macao", "MAF"=> "Saint Martin (French part)", "MAR"=> "Morocco", "MCO"=> "Monaco", "MDA"=> "Moldova, Republic of", "MDG"=> "Madagascar", "MDV"=> "Maldives", "MEX"=> "Mexico", "MHL"=> "Marshall Islands", "MKD"=> "Macedonia, the former Yugoslav Republic of", "MLI"=> "Mali", "MLT"=> "Malta", "MMR"=> "Myanmar", "MNE"=> "Montenegro", "MNG"=> "Mongolia", "MNP"=> "Northern Mariana Islands", "MOZ"=> "Mozambique", "MRT"=> "Mauritania", "MSR"=> "Montserrat", "MTQ"=> "Martinique", "MUS"=> "Mauritius", "MWI"=> "Malawi", "MYS"=> "Malaysia", "MYT"=> "Mayotte", "NAM"=> "Namibia", "NCL"=> "New Caledonia", "NER"=> "Niger", "NFK"=> "Norfolk Island", "NGA"=> "Nigeria", "NIC"=> "Nicaragua", "NOR"=> "Norway", "NIU"=> "Niue", "NLD"=> "Netherlands", "NPL"=> "Nepal", "NRU"=> "Nauru", "NZL"=> "New Zealand", "OMN"=> "Oman", "PAK"=> "Pakistan", "PAN"=> "Panama", "PCN"=> "Pitcairn", "PER"=> "Peru", "PHL"=> "Philippines", "PLW"=> "Palau", "PNG"=> "Papua New Guinea", "POL"=> "Poland", "PRI"=> "Puerto Rico", "PRK"=> "Korea, Democratic People\’s Republic of", "PRT"=> "Portugal", "PRY"=> "Paraguay", "PSE"=> "Palestinian Territory, Occupied", "PYF"=> "French Polynesia", "QAT"=> "Qatar", "REU"=> "Réunion", "ROU"=> "Romania", "RUS"=> "Russian Federation", "RWA"=> "Rwanda", "SAU"=> "Saudi Arabia", "SDN"=> "Sudan", "SEN"=> "Senegal", "SGP"=> "Singapore", "SGS"=> "South Georgia and the South Sandwich Islands", "SHN"=> "Saint Helena", "SJM"=> "Svalbard and Jan Mayen", "SLB"=> "Solomon Islands", "SLE"=> "Sierra Leone", "SLV"=> "El Salvador", "SMR"=> "San Marino", "SOM"=> "Somalia", "SPM"=> "Saint Pierre and Miquelon", "SRB"=> "Serbia", "STP"=> "Sao Tome and Principe", "SUR"=> "Suriname", "SVK"=> "Slovakia", "SVN"=> "Slovenia", "SWE"=> "Sweden", "SWZ"=> "Swaziland", "SYC"=> "Seychelles", "SYR"=> "Syrian Arab Republic", "TCA"=> "Turks and Caicos Islands", "TCD"=> "Chad", "TGO"=> "Togo", "THA"=> "Thailand", "TJK"=> "Tajikistan", "TKL"=> "Tokelau", "TKM"=> "Turkmenistan", "TLS"=> "Timor-Leste", "TON"=> "Tonga", "TTO"=> "Trinidad and Tobago", "TUN"=> "Tunisia", "TUR"=> "Turkey", "TUV"=> "Tuvalu", "TWN"=> "Taiwan, Province of China", "TZA"=> "Tanzania, United Republic of", "UGA"=> "Uganda", "UKR"=> "Ukraine", "UMI"=> "United States Minor Outlying Islands", "URY"=> "Uruguay", "USA"=> "United States", "UZB"=> "Uzbekistan", "VAT"=> "Holy See (Vatican City State)", "VCT"=> "Saint Vincent and the Grenadines", "VEN"=> "Venezuela", "VGB"=> "Virgin Islands, British", "VIR"=> "Virgin Islands, U.S.", "VNM"=> "Viet Nam", "VUT"=> "Vanuatu", "WLF"=> "Wallis and Futuna", "WSM"=> "Samoa", "YEM"=> "Yemen", "ZAF"=> "South Africa", "ZMB"=> "Zambia", "ZWE"=> "Zimbabwe" );
          echo json_encode($country_str);
          exit();
          }

      public function stateAction(){
          $state_str = array("AL"=>"Alabama","AK"=>"Alaska","AZ"=>"Arizona","AR"=>"Arkansas","CA"=>"California","CO"=>"Colorado","CT"=>"Connecticut","DE"=>"Delaware","DC"=>"District Of Columbia","FL"=>"Florida","GA"=>"Georgia","HI"=>"Hawaii","ID"=>"Idaho","IL"=>"Illinois","IN"=>"Indiana","IA"=>"Iowa","KS"=>"Kansas","KY"=>"Kentucky","LA"=>"Louisiana","ME"=>"Maine","MD"=>"Maryland","MA"=>"Massachusetts","MI"=>"Michigan","MN"=>"Minnesota","MS"=>"Mississippi","MO"=>"Missouri","MT"=>"Montana","NE"=>"Nebraska","NV"=>"Nevada","NH"=>"New Hampshire","NJ"=>"New Jersey","NM"=>"New Mexico","NY"=>"New York","NC"=>"North Carolina","ND"=>"North Dakota","OH"=>"Ohio","OK"=>"Oklahoma","OR"=>"Oregon","PA"=>"Pennsylvania","RI"=>"Rhode Island","SC"=>"South Carolina","SD"=>"South Dakota","TN"=>"Tennessee","TX"=>"Texas","UT"=>"Utah","VT"=>"Vermont","VA"=>"Virginia","WA"=>"Washington","WV"=>"West Virginia","WI"=>"Wisconsin","WY"=>"Wyoming");
          echo json_encode($state_str );
          exit();
      }

          public function forgotpasswordAction(){
                    $this->view->title="Forgot Password - Welcome to Rosemoore Lake";
                    if(isset ($_POST["action"])){
                        
                        $emailAddress = $_POST["emailAddress"];

                        $users = new Application_Model_Users();
                        $users->setEmailAddress($emailAddress);

                        $userMapper = new Application_Model_UserMapper();

                       $count =  $userMapper->validateEmail($users);


                       $users->setPassword($users->createRandomPassword());

                       $users->setChangePassword("Y");

                       $users->setUpdatedBy($emailAddress);

                       $date = new Zend_Date();
                       $users->setUpdatedDate($date->getIso());

                       if($count>0){
                          $userMapper->updatePassword($users);
                          $this->mailUser($users);
                          $this->view->message="The password has been sent to your email address";
                       }else{
                           $this->view->users=$users;
                           $this->view->message="Invalid Email Address";
                       }
                     }
          }

           public function changepasswordAction(){
              $this->view->title="Change Password - Welcome to Rosemoore Lake";
              try{
                 if(isset ($_POST["action"])){
                     $password= $_POST["password"];
                     $confirmpassword= $_POST["confirmpassword"];

                     if($password != $confirmpassword){
                         $this->view->message="Passwords do not match";
                     }else{
                         $users = new Application_Model_Users();
                         $users->setEmailAddress(Zend_Auth::getInstance()->getStorage()->read()->EMAIL_ADDRESS);
                         $users->setPassword($password);
                         $users->setChangePassword("N");
                         $users->setUpdatedBy(Zend_Auth::getInstance()->getStorage()->read()->EMAIL_ADDRESS);
                         $date = new Zend_Date();
                         $users->setUpdatedDate($date->getIso());

                         $userMapper = new Application_Model_UserMapper();
                         $userMapper->updatePassword($users);

                           if(Zend_Auth::getInstance()->getStorage()->read()->ADMIN=="Y" && Zend_Auth::getInstance()->getStorage()->read()->RESIDENT !="Y"){
                               $this->_redirect('/admin');
                            }else{
                                $this->_redirect('/resident');
                            }
                    }
                 }
              }catch(Exception $e){
                  Zend_Registry::get('logger')->setEventItem('class', __CLASS__)->err($e->getMessage());
                  $this->view->message="Technical difficulties in updating password";
              }
           }

           public function changeroleAction(){
               if(isset ($_GET["action"])){
                   $role=$_GET['role'];
                   if($role == "A"){
                        $this->_redirect('/admin');
                   }else if($role == "R"){
                          $this->_redirect('/resident');
                   }
               }
           }



         private function mailUser(Application_Model_Users $users){
          try{
                   require_once "Mail.php";

                    $config = Zend_Registry::get('mail_config');

                     $from = "Rosemoore Lake<administrator@rosemoorelake.org>";
                     $to =$users->getEmailAddress();
                     $subject = "Your Rosemoore Lake password has been reset successfully";
                     $body =  "Hi, \n\nYour Rosemoore Lake password has been successfully reset to ".$users->getPassword().". Please change your password once you login. \n \nThanks,\n \nAdministrator";

                      $host = $config->mail->host;
                     $username = $config->mail->username;
                     $password =$config->mail->password;
                     $port =$config->mail->port;


                     $headers = array ('From' => $from,
                       'To' => $to,
                       'Subject' => $subject);

                     $smtp = Mail::factory('smtp',
                       array ('host' => $host,
                         'auth' => true,
                         'port'=>$port,
                         'username' => $username,
                         'password' => $password));


                       $mail = $smtp->send($to, $headers, $body);

                        if (PEAR::isError($mail)) {
                       
                        }else{
                            
                        }
                     
              }catch(Exception $e){
                  Zend_Registry::get('logger')->setEventItem('class', __CLASS__)->err($e->getMessage());
              }

          }
}